//
//  SearchCodeController.m
//  QQplayground
//
//  Created by zhangxy on 2018/6/5.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "SearchCodeController.h"
#import "ProvinceEntity.h"
#import "XMLReader.h"

@interface SearchCodeController ()

@property(nonatomic,strong) ZTextField *txtSearch;
@property(nonatomic,strong)  NSMutableArray *listArray;
@property(nonatomic,strong)  UITableView *listTable;
@property(nonatomic,strong)  NSMutableDictionary *allKeysList;

@end

@implementation SearchCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIImage *backImage =[UIImage imageNamed:@"base_bg.jpg"];
    self.view.layer.contents=(id)backImage.CGImage;
    //    self.view.layer.backgroundColor = [UIColor clearColor].CGColor;
    self.view.layer.backgroundColor = UIColorFromRGB(0x67ACA6).CGColor;
    
    
    [self createTitleMenu];
    [self.menuTitleButton setTitle:@"选择国家/地区" forState:0];
    [self.titleMenu setBackgroundColor:UIColor.clearColor];
    
    [self.menuLeftButton setImage:[UIImage imageNamed:@"btn_back_title_sel"] forState:UIControlStateNormal];
    [self.menuLeftButton setImage:[UIImage imageNamed:@"btn_back_title_sel"] forState:UIControlStateHighlighted];
    
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenKeyboard:)];
//    [self.view addGestureRecognizer:tap];
//
//    UIView *itemBgView = [[UIView alloc] initWithFrame:CGRectMake(20, NavBarHeight, ScreenWidth-40, 44)];
//    itemBgView.layer.cornerRadius = 11.0f;
//    itemBgView.layer.masksToBounds  = YES;
//    [itemBgView setBackgroundColor:UIColorFromRGB(TextWhiteColor)];
//    [self.view addSubview:itemBgView];
//
//
//    UIButton *btnTemp = [[UIButton alloc] initWithFrame:CGRectMake(15, 8, 28, 28)];
//    [btnTemp.titleLabel setFont:FontSeventeen];
//    [btnTemp setTitleColor:UIColorFromRGB(BgTitleColor) forState:0];
//    [btnTemp setTitle:@"" forState:0];
//    [btnTemp setImage:[UIImage imageNamed:@"icon_serach"] forState:0];
//    [itemBgView addSubview:btnTemp];
//
//    _txtSearch =  [ZZViewUtils createZTextField:@"搜索国家/地区"];
//    [_txtSearch setFrame:CGRectMake(58, 3.5, ScreenWidth - 40 - 58, 35)];
//    [itemBgView addSubview:_txtSearch];
    
    
    [self createTableView];
}



// 隐藏键盘
-(void)hiddenKeyboard:(id)sender
{
    [_txtSearch resignFirstResponder];
}


-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    _allKeysList = [[NSMutableDictionary alloc] init];
    
    _listTable=[self.view createTableView:self];
    [_listTable setFrame:CGRectMake(0, NavBarHeight, ScreenWidth, ScreenHeight - NavBarHeight)];
    
    [_listTable setBackgroundColor:UIColor.clearColor];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    if ([_listTable respondsToSelector:@selector(sectionIndexColor)])
    {
        _listTable.sectionIndexColor = UIColorFromRGB(TextWhiteColor);
    }
    
    
    [self setTableSeparatorInset];
    
    [self loadBegin];
}

-(void)loadBegin{
    [_listArray removeAllObjects];
    [self loadMoreData];
}

-(void) sortArray{
    
    //遍历成员列表，将成员名字 contactName 转成拼音，并存放到 categoryName 字段中，用于排序
//     [_listArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        ProvinceEntity *contact = (ProvinceEntity *)obj;
//        NSString *outputPinyin= transformPinYin(contact.name);
//        contact.pyName = [outputPinyin uppercaseString];
//    }];
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"pyName" ascending:YES];
    NSArray *array = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [_listArray sortUsingDescriptors:array];
}

/**
 加载更多
 */
-(void)loadMoreData{
    NSString *xmlFileString = [[NSBundle mainBundle] pathForResource:@"region_arrays" ofType:@"xml"];
    NSData *xmlData = [NSData dataWithContentsOfFile:xmlFileString];
    NSError *error = nil;
    
    NSDictionary *result = [XMLReader dictionaryForXMLData:xmlData error:&error];
    if (!error) {
        NSArray *arr = result[@"resources"][@"string-array"][@"item"];
        for(int i =0 ;i< arr.count;i++){
            NSDictionary *textDict = arr[i];
            NSArray *arrItem = [textDict[@"text"] componentsSeparatedByString:@" "];
            ProvinceEntity *p = [[ProvinceEntity alloc] init];
            p.name = arrItem[1];//[str substringWithRange:NSMakeRange(arc4random() % (str.length-2), 2)];
            p.area_code = arrItem[2];
            p.pyName = [arrItem[0] uppercaseString];//transformPinYin(p.name);
            [self.listArray addObject:p];
        }
        
        
        [self sortArray];
        [_listTable reloadData];
    }
}


#pragma mark UITableView delegate Start
//右边索引 字节数(如果不实现 就不显示右侧索引)
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *toBeReturned = [[NSMutableArray alloc]init];
    for(char c = 'A';c<='Z';c++)
        [toBeReturned addObject:[NSString stringWithFormat:@"%c",c]];
    
    return toBeReturned;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSInteger count = 0;
    for(ProvinceEntity *character in _listArray)
    {
        if([character.pyName hasPrefix:title])
        {
            [_listTable setContentOffset:CGPointMake(0, 44*count) animated:NO];
            return count;
        }
        count ++;
    }
    return 0;
}

//section （标签）标题显示
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
//    if([_listArray count]==0)
//    {
        return @"";
//    }
//    return [_listArray objectAtIndex:section];
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    if(section == 0){
        
    }
    return headerView;
}

// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _listArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ids = @"CELL_ID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ids];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ids];
    }
    cell.backgroundColor = UIColor.clearColor;
    cell.textLabel.textColor = UIColorFromRGB(TextWhiteColor);
    cell.textLabel.font = FontFiftent;
    ProvinceEntity *entity = [_listArray objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",entity.name,entity.pyName];
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ProvinceEntity *model=[_listArray objectAtIndex:indexPath.row];
    if(_ZZPageResultBlock){
        _ZZPageResultBlock(model.area_code);
    }
    [self backAction];
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if((indexPath.section+1) < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
